package com.yesep.learn.design.behavioral.interpreter.calculator;

import java.util.*;
import java.util.function.*;

public class Context {
    private final Map<String, Double> variables = new HashMap<>();
    private final Map<String, Function<Double, Double>> functions = new HashMap<>();

    public Context() {
        // 初始化内置函数
        functions.put("square", x -> x * x);
        functions.put("cube", x -> x * x * x);
    }

    public void setVariable(String variableName, double value) {
        variables.put(variableName, value);
    }

    public Double getVariable(String variableName) {
        return variables.getOrDefault(variableName, 0D);
    }

    public double callFunction(String functionName, double argument) {
        Function<Double, Double> function = functions.get(functionName);
        if (function == null) {
            throw new IllegalArgumentException("Unknown function: " + functionName);
        }
        return function.apply(argument);
    }
}